<template>
  <div class="table-panel">
    <!-- <div class="camera-height"></div> -->
    <div class="fixed-top">
      <div id="sidebar">
        <h1>身份证信息导入</h1>
      </div>
      <div class="camera row">
        <div id="noniediv">
          <p class="xform-p"></p>
          <p id="streamwrap" class="xform-p">
            <img id="ImgMain" class="xform" WIDTH="400" HEIGHT="300" />
            <img id="ImgAssis" class="xform" WIDTH="400" HEIGHT="300" />
          </p>
        </div>

        <!-- 如果是ie浏览器，会显示ocx -->
        <div id="ocxdiv">
          <OBJECT
            classid="clsid:A4B4E9B5-78E6-4CE3-B8A1-4B36237943F8"
            id="ocxstreamimage"
            name="showVideoOcx"
            width="360px"
            height="270px"
          ></OBJECT>
          <OBJECT
            classid="clsid:A4B4E9B5-78E6-4CE3-B8A1-4B36237943F8"
            id="ocxstreamimage1"
            name="showVideoOcx1"
            width="360px"
            height="270px"
          ></OBJECT>
        </div>
        <div class="operate-button column">
          <el-button type="primary" @click="OpenMainCamera">打开主头</el-button>
          <el-button type="primary" @click="CloseMainCamera"
            >关闭主头</el-button
          >
          <el-button type="primary" @click="OpenAssisCamera"
            >打开副头</el-button
          >
          <el-button type="primary" @click="CloseAssisCamera"
            >关闭副头</el-button
          >
        </div>
      </div>
    </div>

    <div class="operate-item row">
      <div class="op-item-left">
        <el-button type="primary" @click="GetEquipmentType"
          >获取设备型号</el-button
        >
      </div>
      <div class="op-item-right" style="height: 40px; line-height: 40px">
        {{ eqType }}
      </div>
    </div>
    <div class="operate-item row">
      <div class="op-item-left">
        <el-button type="primary" @click="GrabImageBase64">获取图片</el-button>
      </div>
      <div>
        <label style="height: 40px; line-height: 40px">副摄像头图片</label>
        <div>
          <img
            v-if="snapshotSrc != ''"
            id="snapshot"
            :src="snapshotSrc"
            alt="This is a static snapshot"
            width="320px"
            height="200px"
          />
          <img v-else src="./photo.png" />
        </div>
      </div>
    </div>
    <div
      class="operate-item row"
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
    >
      <div class="op-item-left">
        <el-button type="primary" @click="ReadIDCard">读身份证</el-button>
      </div>
      <div>
        <label style="height: 40px; line-height: 40px">身份证信息</label>
        <el-form :model="IDCardInfo" disabled label-width="120px">
          <el-form-item label="姓名：">
            <el-input v-model="IDCardInfo.name"></el-input>
          </el-form-item>
          <el-form-item label="性别：">
            <el-input v-model="IDCardInfo.sex"></el-input>
          </el-form-item>
          <el-form-item label="民族：">
            <el-input v-model="IDCardInfo.nationCode"></el-input>
          </el-form-item>
          <el-form-item label="生日：">
            <el-input v-model="IDCardInfo.birthday"></el-input>
          </el-form-item>
          <el-form-item label="地址：">
            <el-input v-model="IDCardInfo.address"></el-input>
          </el-form-item>
          <el-form-item label="身份证号：">
            <el-input v-model="IDCardInfo.cardID"></el-input>
          </el-form-item>
          <el-form-item label="发卡机构：">
            <el-input v-model="IDCardInfo.issueOrgan"></el-input>
          </el-form-item>
          <el-form-item label="有效时间：">
            <el-input
              v-model="IDCardInfo.validStart"
              style="width: 130px"
            ></el-input
            >~
            <el-input
              v-model="IDCardInfo.validEnd"
              style="width: 130px"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-left: 100px">
        <label>证件照</label><br />
        <div>
          <img
            v-if="photoSrc != ''"
            id="photo"
            :src="photoSrc"
            alt="This is a photo"
            width="200px"
            height="240px"
          />
          <img v-else src="./photo.png" />
        </div>
        <div>
          <label>身份证正面</label><br />
          <div>
            <img
              v-if="photo1Src != ''"
              id="photo1"
              :src="photo1Src"
              alt="This is a photo"
              width="400px"
              height="200x"
            />
            <img v-else src="./photo.png" />
          </div>
        </div>
        <div>
          <label>身份证反面</label><br />
          <img
            v-if="photo2Src != ''"
            id="photo2"
            :src="photo2Src"
            alt="This is a photo"
            width="400"
            height="200px"
          />
          <img v-else src="./photo.png" />
        </div>
      </div>
    </div>
    <div class="operate-item row">
      <div class="op-item-left">
        <el-button type="primary" @click="FaceComparisonEx">人证比对</el-button>
      </div>
      <label style="height: 40px; line-height: 40px">{{
        faceComparisonExRes
      }}</label>
    </div>
    <!-- <el-descriptions title="用户信息">
      <el-descriptions-item label="姓名">{{
        IDCardInfo.name
      }}</el-descriptions-item>
      <el-descriptions-item label="性别">{{
        IDCardInfo.sex
      }}</el-descriptions-item>
      <el-descriptions-item label="民族">{{
        IDCardInfo.nationCode
      }}</el-descriptions-item>
      <el-descriptions-item label="生日">{{
        IDCardInfo.birthday
      }}</el-descriptions-item>
      <el-descriptions-item label="地址">{{
        IDCardInfo.address
      }}</el-descriptions-item>
      <el-descriptions-item label="身份证号">{{
        IDCardInfo.cardID
      }}</el-descriptions-item>
      <el-descriptions-item label="发卡机构">{{
        IDCardInfo.issueOrgan
      }}</el-descriptions-item>
      <el-descriptions-item label="有效时间"
        >{{ IDCardInfo.validStart }}~{{
          IDCardInfo.validEnd
        }}</el-descriptions-item
      >
      <el-descriptions-item label="证件照"></el-descriptions-item>
      <el-descriptions-item label="身份证正面"></el-descriptions-item>
      <el-descriptions-item label="身份证反面"></el-descriptions-item>
    </el-descriptions> -->
    <div id="result"></div>
    <br />
    <div class="checkFiling">
      <el-button type="primary" @click="clean">清空信息</el-button>
      <el-button type="primary" @click="submit">{{isUpdate?"确认修改":"确认建档"}}</el-button>
    </div>

    <br />
    <br />
    <div id="container" style="float: left" width="320px" height="200px"></div>
    <br />
    <!-- <div class="show-result">
      <textarea cols="185" rows="25" id="objLog" name="objLog"></textarea>
    </div> -->
  </div>
</template>

<script type="text/javascript" src="jquery.js"></script>    
    <script type="text/javascript" src="jquery.rotate.js"></script>
	<script type="text/javascript" src="./jquery-2.0.3.min.js"></script> 
    <!--[if IE 6]>
    <link rel="stylesheet" href="fix.css" type="text/css" />
	<![endif]-->
	<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
import { insertPersonnel, updatePersonnel } from "@/api/worker.js";
import axios from "axios";
export default {
  data() {
    return {
      loading: false,
      faceComparisonExRes: "人证比对结果",
      photoSrc: "",
      photo1Src: "",
      photo2Src: "",
      snapshotSrc: "",
      phi: 0,
      camidx: 0,
      uuid: "",
      filepath: "",
      filelist: "",
      isIE: false,
      IdBase64: "",
      FaceBase64: "",
      IDCardInfo: {},
      index: 1,
      imgPathArray: new Array(),
      imgPathToPdfArray: new Array(),
      head: "123",
      facade: "",
      obverse: "",
      eqType: "",
      img: {},
      timer: null,
      comparison: false,
      isUpdate:false,
      BASE_API: process.env.BASE_API,
    };
  },
  created() {
    // console.log(this.$route.query.personId);
    if(this.$route.query.personId!=undefined){
      this.isUpdate = true
    }
  },
  mounted() {
    this.Init();
  },
  methods: {
    //初始化
    Init() {
      var isIE = this.IsIE();
      this.GetEquipmentType(); //如果不调用获取不到设备型号，签名功能可能会失败。
      if (isIE) {
        //ie浏览器
        var ui = document.getElementById("noniediv");
        ui.style.display = "none";
        ui.style.visibility = "hidden";
        showVideoOcx.StartPreview(0);
        showVideoOcx1.StartPreview(1);
      } else {
        var ui = document.getElementById("ocxdiv");
        ui.style.display = "none";
        ui.style.visibility = "hidden";
        this.OpenMainCamera();
        this.OpenAssisCamera();
      }
    },
    IsIE() {
      if (this.BrowserType() == "IE") return true;
      else return false;
    },
    BrowserType() {
      var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
      if (userAgent.indexOf("Firefox") > -1) return "Firefox";
      if (userAgent.indexOf("Chrome") > -1) return "Chrome";

      return "IE";
    },
    GetEquipmentType() {
      var params = "";
      var url = "http://127.0.0.1:38088/device=getequipmenttype";
      axios({
        method: "post",
        url: url,
        dataType: "json",
        data: params,
      }).then((res) => {
        const data = res.data;
        if (data.code == 0) {
          var date = new Date().toLocaleString();
          // this.log(date + "\t" + "设备型号：" + data.data);
          this.eqType = data.data;
        } else {
          var date = new Date().toLocaleString();
          // this.log(date + "\t" + "获取设备型号失败");
          this.eqType = "获取设备型号失败";
        }
      });
    },
    OpenMainCamera() {
      //<img id="ImgMain" class="xform" src="http://127.0.0.1:38088/video=stream&camidx=0" WIDTH="600" HEIGHT="400"/>

      document.getElementById("ImgMain").src =
        "http://127.0.0.1:38088/video=stream&camidx=0";
    },
    CloseMainCamera() {
      //document.getElementById("ImgMain").src = "";

      var params = '{"camidx":"0"}';
      var url = "http://127.0.0.1:38088/video=close";

      axios({
        method: "post",
        url: url,
        dataType: "json",
        data: params,
      }).then((res) => {
        const data = res.data;
        if (data.code == 0) {
          var date = new Date().toLocaleString();
          // this.log(date + "\t" + "关闭视频成功");
          document.getElementById("ImgMain").src = "";
        } else {
          var date = new Date().toLocaleString();
          // this.log(date + "\t" + "关闭视频失败");
        }
      });
    },
    OpenAssisCamera() {
      //<img id="ImgAssisi" class="xform" src="http://127.0.0.1:38088/video=stream&camidx=1" WIDTH="600" HEIGHT="400"/>

      document.getElementById("ImgAssis").src =
        "http://127.0.0.1:38088/video=stream&camidx=1";
    },
    CloseAssisCamera() {
      //document.getElementById("ImgAssis").src = "";

      var params = '{"camidx":"1"}';
      var url = "http://127.0.0.1:38088/video=close";

      axios({
        method: "post",
        url: url,
        dataType: "json",
        data: params,
      }).then((res) => {
        const data = res.data;
        if (data.code == 0) {
          var date = new Date().toLocaleString();
          // this.log(date + "\t" + "关闭视频成功");
          document.getElementById("ImgAssis").src = "";
        } else {
          var date = new Date().toLocaleString();
          // this.log(date + "\t" + "关闭视频失败");
        }
      });
    },
    convertBase64UrlToBlob(urlData, fileName) {
      var bytes = window.atob(urlData.split(",")[0]); //去掉url的头，并转换为byte
      //处理异常,将ascii码小于0的转换为大于0
      var ab = new ArrayBuffer(bytes.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      const blob = new Blob([ab], { type: "image/jpeg" });
      blob.lastModifiedDate = new Date();
      let file = new File([blob], fileName, { type: "image/jpeg" });
      return file;
    },
    toFormdata(file) {
      const formdata = new FormData();
      formdata.append("file", file);
      return formdata;
    },
    ReadIDCard() {
      this.IdBase64 = "";
      this.loading = true;
      // document.getElementById("result").innerHTML =
      //   "二代证信息获取请求中......";
      var params = "";
      var url = "http://127.0.0.1:38088/card=idcard";
      axios({
        method: "post",
        url: url,
        dataType: "json",
        data: params,
      }).then((res) => {
        this.loading = false;
        const data = res.data;
        console.log("data",data);
        if (data.code != 0) {
          this.$alert("读取身份证信息失败!", "错误", {
            confirmButtonText: "确定",
            callback: (action) => {
              this.$message({
                type: "info",
                message:
                  "返回代码 = " + data.code + " 返回信息 = " + data.message,
              });
            },
          });
          // document.getElementById("result").innerHTML =
          //   "ReadIDCard 失败<br />返回代码 = " +
          //   data.code +
          //   "<br />  返回信息 = " +
          //   data.message;
        } else {
          // document.getElementById("result").innerHTML =
          //   "ReadIDCard <br />返回代码：" +
          //   data.code +
          //   "<br />返回信息：" +
          //   data.message +
          //   "<br />姓名：" +
          //   data.IDCardInfo.name +
          //   "<br />性别：" +
          //   data.IDCardInfo.sex +
          //   "<br />民族：" +
          //   data.IDCardInfo.nationCode +
          //   "<br />生日：" +
          //   data.IDCardInfo.birthday +
          //   "<br />地址：" +
          //   data.IDCardInfo.address +
          //   "<br />身份证号：" +
          //   data.IDCardInfo.cardID +
          //   "<br />发卡机构：" +
          //   data.IDCardInfo.issueOrgan +
          //   "<br />有效时间：" +
          //   data.IDCardInfo.validStart +
          //   "-" +
          //   data.IDCardInfo.validEnd;
          this.photoSrc =
            "data:image/jpeg;base64," + data.IDCardInfo.photoBase64;
          // // document.getElementById("photo").src =
          // //   "data:image/jpeg;base64," + data.IDCardInfo.photoBase64;
          this.photo1Src =
            "data:image/jpeg;base64," + data.IDCardInfo.photoBase64_Z;
          // // document.getElementById("photo1").src =
          // //   "data:image/jpeg;base64," + data.IDCardInfo.photoBase64_Z;
          // // document.getElementById("photo2").src =
          // //   "data:image/jpeg;base64," + data.IDCardInfo.photoBase64_F;
          this.photo2Src =
            "data:image/jpeg;base64," + data.IDCardInfo.photoBase64_F;
          this.IDCardInfo = data.IDCardInfo;
          this.IdBase64 = data.IDCardInfo.photoBase64;
        }
        // console.log(res.data)

        // console.log(this.IDCardInfo);
        this.uploadImg();
      });
    },
    uploadImg() {
      var IDCardInfo = this.IDCardInfo;
      var cardId = IDCardInfo.cardID;
      var img = this.img;
      var headFile = this.convertBase64UrlToBlob(
        IDCardInfo.photoBase64,
        `${cardId}H.jpg`
      );
      var faceFile = this.convertBase64UrlToBlob(
        IDCardInfo.photoBase64_Z,
        `${cardId}F.jpg`
      );
      var backFile = this.convertBase64UrlToBlob(
        IDCardInfo.photoBase64_F,
        `${cardId}B.jpg`
      );
      axios
        .post(
          BASE_API+'/sys/file/uploadImg',
          this.toFormdata(headFile)
        )
        .then((res) => {
          console.log(res);
          img.head = res.data.data.imgurl;
        })
        .catch((res) => {
          console.log(1, res);
        });
      axios
        .post(
          BASE_API+'/sys/file/uploadImg',
          this.toFormdata(faceFile)
        )
        .then((res) => {
          console.log(res);
          img.facade = res.data.data.imgurl;
        })
        .catch((res) => {
          console.log(1, res);
        });
      axios
        .post(
          BASE_API+'/sys/file/uploadImg',
          this.toFormdata(backFile)
        )
        .then((res) => {
          console.log(res);
          img.obverse = res.data.data.imgurl;
        })
        .catch((res) => {
          console.log(1, res);
        });
      this.img = img;
    },
    submit() {
      if (this.comparison == true) {
        var IDCardInfo = this.IDCardInfo;
        var sex = IDCardInfo.sex;
        if (sex == "男") sex = 1;
        else sex = 0;
        var str = IDCardInfo.birthday;
        var birthDate =
          str.substring(0, 4) +
          "-" +
          str.substring(4, 6) +
          "-" +
          str.substring(6, 8);
        // console.log(str);
        // console.log(birthDate);
        // console.log(this.head);
        var clan = IDCardInfo.nationCode;
        var str1 = IDCardInfo.validEnd;
        var validEnd =
          str1.substring(0, 4) +
          "-" +
          str1.substring(4, 6) +
          "-" +
          str1.substring(6, 8);
        // console.log(this.img);
        // console.log(this.img.head);
        // console.log(this.img.facade);
        // console.log(this.img.obverse);
        const data = {
          name: IDCardInfo.name,
          hometown: IDCardInfo.address,
          birthDate: birthDate,
          certificateNumber: IDCardInfo.cardID,
          gender: sex,
          idPhoto: this.img.head, //证件照
          idPhotoPositive: this.img.facade, //正面
          idPhotoObverse: this.img.obverse, //反面
          certificateType: "居民身份证",
          clan: clan,
          certificateValidPeriod: validEnd,
          country: "中国",
          status: 0,
          openAccount: 0,
          bankName: IDCardInfo.name,
        };
        if (this.isUpdate) {
          data.personId = this.$route.query.personId;
          updatePersonnel(data)
            .then((res) => {
              this.$message({
                type: "success",
                message: "修改成功！",
              });
              this.$router.push({ path: "/worker/add", query: { id: this.$route.query.personId } });
            })
            .catch((res) => {
              console.log(res);
            });
        } else {
          insertPersonnel(data)
            .then((res) => {
              console.log(res);
              this.$message({
                type: "success",
                message: "添加成功！",
              });
            })
            .catch((res) => {
              console.log(res);
            });
        }
      } else {
        this.$message({
          type: "error",
          message: "人证比对失败",
        });
      }
    },
    // 获取图片base64
    GrabImageBase64() {
      this.FaceBase64 = "";
      var cutpage = document.getElementsByName("cutpage");
      var params =
        '{"filepath":"base64","rotate":"' +
        this.phi.toString() +
        '","camidx":"1","cutpage":"' +
        "0" +
        '"}';
      var url = "http://127.0.0.1:38088/video=grabimage";

      axios({
        method: "post",
        url: url,
        dataType: "json",
        data: params,
      }).then((res) => {
        const data = res.data;
        this.FaceBase64 = data.photoBase64;
        var date = new Date().toLocaleString();
        this.snapshotSrc = "data:image/jpg;base64," + data.photoBase64;
        // this.log(date + "\t" + "获取图片base64数据：" + data.photoBase64);
        //document.getElementById("snapshot").src = "data:image/jpg;base64," + data.data;
        // document.getElementById("snapshot").src =
        //   "data:image/jpg;base64," + data.photoBase64;
        document.getElementById("result").innerHTML = "";
      });
    },
    // 人证对比
    FaceComparisonEx() {
      this.faceComparisonExRes = "对比中...";
      var params =
        '{"FaceOne":"' +
        this.IdBase64.toString() +
        '","FaceTwo":"' +
        this.FaceBase64.toString() +
        '"}';
      var url = "http://127.0.0.1:38088/comparison=imgdata";
      axios({
        method: "post",
        url: url,
        dataType: "json",
        data: params,
      }).then((res) => {
        const data = res.data;
        if (data.data > 50) this.comparison = true;
        if (data.code == 0) {
          var date = new Date().toLocaleString();
          // this.log(
          //   date +
          //     "\t" +
          //     "人证比对值一般大于50可以认为是同一个人，比对值为：" +
          //     data.data
          // );
          this.faceComparisonExRes =
            date +
            "\t" +
            "人证比对值一般大于50可以认为是同一个人，比对值为：" +
            data.data;
        } else if (data.code != 0) {
          var date = new Date().toLocaleString();
          // this.log(date + "\t" + "错误原因：" + data.data);
          this.faceComparisonExRes = date + "\t" + "错误原因：" + data.data;
        }
      });
    },
    log(s) {
      var oldValue = document.getElementById("objLog").value;
      if (oldValue.length > 0) {
        oldValue += "\n";
      }

      document.getElementById("objLog").value = s + "\n" + oldValue;
    },
    clean() {
      // document.getElementById("objLog").value = "";
      this.snapshotSrc = "";
      this.IDCardInfo = {};
      this.faceComparisonExRes = "人证比对结果";
      this.photoSrc = "";
      this.photo1Src = "";
      this.photo2Src = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.column {
  display: flex;
  flex-direction: column;
}
.row {
  display: flex;
  flex-direction: row;
}
.camera-height {
  height: 440px;
  width: 100%;
}
// .fixed-top{
// background-color: #ffffff;
//  position: fixed;
//   top: 120px;
//   z-index: 2;
//   right: 20px;
//   width: 80%;
// }
.camera {
  width: 100%;
  text-align: center;
  // justify-content: space-around;

  .noniediv p {
    width: 900px;
  }
}
.operate-button {
  margin-top: 20px;
  height: 300px;
  flex-grow: 2;
  // text-align: center;
  justify-content: space-between;
  .el-button {
    width: 150px;
    // margin-left: 0;
    margin: auto auto;
  }
}
.operate-item {
  margin-top: 20px;
  .op-item-left {
    width: 150px;
  }
  .el-button {
    height: 40px;
    width: 126px;
  }
  .el-form {
    width: 400px;
  }
}

.show-result {
  width: 100%;
  textarea {
    width: 100%;
  }
}
.checkFiling {
  width: 100%;
  text-align: right;
}
</style>